package com.lecture.java8.cmd;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

public class LinuxCmdExecutor {

    private CmdResult result;

    public LinuxCmdExecutor(CmdResult result) {
        this.result = result;
    }

    public CmdResult execute(String cmd) {
        System.out.println("获取命令:" + cmd);
        CmdEntity entity = CmdLook.parseToJavaCmdEntity(cmd);
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(entity.getSegment());
            InputStream stdout = process.getInputStream();
            InputStream stderr = process.getErrorStream();
            Thread stdoutThread = new Thread(() -> {
                LinuxCmdExecutor.this.readStream(LinuxCmdExecutor.this.result,stdout,true);
            });
            Thread stderrThread = new Thread(() -> {
                LinuxCmdExecutor.this.readStream(LinuxCmdExecutor.this.result,stderr,false);
            });
            stdoutThread.start();
            stderrThread.start();

            stdoutThread.join();
            stderrThread.join();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        process.destroy();
        return this.result;
    }

    public void readStream(CmdResult result, InputStream stream,boolean isStderr) {
        BufferedReader reader = null;
        try {
            String os = System.getProperty("os.name");
            if (os.contains("Windows")) {
                reader = new BufferedReader(new InputStreamReader(stream));
            } else {
                reader = new BufferedReader(new InputStreamReader(stream, Charset.forName("UTF-8")));
            }
            while (true) {
                String line = reader.readLine();
                System.out.println("获取数据：" + line);
                if (line == null) {
                    break;
                }
                if (StringUtils.isNoneBlank(line)) {
                    if (isStderr) {
                        result.appendStderrNewLine(line);
                    } else {
                        result.appendStdoutNewLine(line);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }
}
